﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InstantSpine.Core
{
    /// <summary>
    /// Quick and dirty CSV reader/writer
    /// </summary>
    static class CSVTools
    {
        public static void Save(IEnumerable<string> header,
                                IEnumerable<IEnumerable<string>> rows,
                                string filename,
                                char delimiter = '\t') {
            using (var csvfile = System.IO.File.CreateText(filename)) {
                csvfile.WriteLine(header.Aggregate((h1, h2) => h1 + delimiter + h2));
                foreach (var row in rows) {
                    csvfile.WriteLine(row.Aggregate((v1, v2) => v1 + delimiter + v2));
                }
            }
        }

        public static IEnumerable<IEnumerable<string>> Load(string filename,
                                                            bool skipHeader = true,
                                                            char delimiter = '\t') {
            var csvContents = new List<IEnumerable<string>>();
            using (var csvfile = System.IO.File.OpenText(filename)) {
                if (skipHeader) csvfile.ReadLine();
                string line = null;
                while ((line = csvfile.ReadLine()) != null) {
                    csvContents.Add(line.Split(delimiter));
                }
            }
            return csvContents;
        }
    }
}
